{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "ee-api-colab-setup.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.sandbox.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/ee-api-colab-setup.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LAZiVi13zTE7",
        "colab_type": "text"
      },
      "source": [
        "# Earth Engine Python API Colab Setup\n",
        "\n",
        "This notebook demonstrates how to setup the Earth Engine Python API in Colab and provides several examples of how to print and visualize Earth Engine processed data.\n",
        "\n",
        "## Install API and get credentials\n",
        "\n",
        "Using the Earth Engine API in Google Colaboratory requires installing the API and authenticating. These steps must be completed for each new Colab session or if you restart your Colab kernel or if your Colab virtual machine is recycled due to inactivity.\n",
        "\n",
        "### Install the API\n",
        "\n",
        "This step will install the Earth Engine Python API and `earthengine` command line\n",
        "tool in the Colab virtual machine using the `pip` package installer. Run the following cell to install the API to your session."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "65RChERMzQHZ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "!pip install earthengine-api"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s-dN42MTzg-w",
        "colab_type": "text"
      },
      "source": [
        "### Authenticate\n",
        "\n",
        "Import the Earth Engine API and run the `ee.Authenticate` function to authenticate your access to Earth Engine servers. Upon running the cell you'll be asked to grant Earth Engine access to your Google account. Follow the instructions printed to the cell."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NMp9Ei9b0XXL",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Import the Earth Engine library.\n",
        "import ee\n",
        "\n",
        "# Trigger the authentication flow.\n",
        "ee.Authenticate()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8I_Fr0L5AFmu",
        "colab_type": "text"
      },
      "source": [
        "### Test the API\n",
        "\n",
        "Test the API by printing the elevation of Mount Everest. Note that before using the API you must initialize it."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "v7pD6pDOAhOW",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Initialize the library.\n",
        "ee.Initialize()\n",
        "\n",
        "# Print the elevation of Mount Everest.\n",
        "dem = ee.Image('USGS/SRTMGL1_003')\n",
        "xy = ee.Geometry.Point([86.9250, 27.9881])\n",
        "elev = dem.sample(xy, 30).first().get('elevation').getInfo()\n",
        "print('Mount Everest elevation (m):', elev)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fDLAqiNWeD6t",
        "colab_type": "text"
      },
      "source": [
        "## Map visualization\n",
        "\n",
        "`ee.Image` objects can be displayed to notebook output cells. The following two\n",
        "examples demonstrate displaying a static image and an interactive map.\n",
        "\n",
        "### Static image\n",
        "\n",
        "The `IPython.display` module contains the `Image` function, which can display\n",
        "the results of a URL representing an image generated from a call to the Earth\n",
        "Engine `getThumbUrl` function. The following cell will display a thumbnail\n",
        "of the SRTM global elevation model."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Fp4rdpy0eGjx",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Import the Image function from the IPython.display module. \n",
        "from IPython.display import Image\n",
        "\n",
        "# Display a thumbnail of global elevation.\n",
        "Image(url=dem.getThumbUrl({'min': 0, 'max': 3000}))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ljo5dbLkfmVm",
        "colab_type": "text"
      },
      "source": [
        "### Interactive map\n",
        "\n",
        "The [`folium`](https://python-visualization.github.io/folium/)\n",
        "library can be used to display `ee.Image` objects on an interactive\n",
        "[Leaflet](https://leafletjs.com/) map. Folium has no default\n",
        "method for handling tiles from Earth Engine, so one must be defined\n",
        "and added to the `folium.Map` module before use.\n",
        "\n",
        "The following cell provides an example of adding a method for handing Earth Engine\n",
        "tiles and using it to display an elevation model to a Leaflet map."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "VIiyf6azf4mU",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Import the Folium library.\n",
        "import folium\n",
        "\n",
        "# Define a method for displaying Earth Engine image tiles to folium map.\n",
        "def add_ee_layer(self, eeImageObject, visParams, name):\n",
        "  mapID = ee.Image(eeImageObject).getMapId(visParams)\n",
        "  folium.raster_layers.TileLayer(\n",
        "    tiles = \"https://earthengine.googleapis.com/map/\"+mapID['mapid']+\n",
        "      \"/{z}/{x}/{y}?token=\"+mapID['token'],\n",
        "    attr = \"Map Data &copy; <a href='https://earthengine.google.com/'>Google Earth Engine</a>\",\n",
        "    name = name,\n",
        "    overlay = True,\n",
        "    control = True\n",
        "  ).add_to(self)\n",
        "\n",
        "# Add EE drawing method to folium.\n",
        "folium.Map.add_ee_layer = add_ee_layer\n",
        "\n",
        "# Set visualization parameters.\n",
        "visParams = {'min':0, 'max':3000, 'palette':['225ea8','41b6c4','a1dab4','ffffcc']}\n",
        "\n",
        "# Create a folium map object.\n",
        "myMap = folium.Map(location=[20, 0], zoom_start=3, height=500)\n",
        "\n",
        "# Add the elevation model to the map object.\n",
        "myMap.add_ee_layer(dem, visParams, 'DEM')\n",
        "\n",
        "# Add a layer control panel to the map.\n",
        "myMap.add_child(folium.LayerControl())\n",
        "\n",
        "# Display the map.\n",
        "display(myMap)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CYfinjFhg0HN",
        "colab_type": "text"
      },
      "source": [
        "## Chart visualization\n",
        "\n",
        "Some Earth Engine functions produce tabular data that can be plotted by\n",
        "data visualization packages such as `matplotlib`. The following example\n",
        "demonstrates the display of tabular data from Earth Engine as a scatter\n",
        "plot. See [Charting in Colaboratory](https://colab.sandbox.google.com/notebooks/charts.ipynb)\n",
        "for more information."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tRPULejJhBSl",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Import the matplotlib.pyplot module.\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Fetch a Landsat image.\n",
        "img = ee.Image('LANDSAT/LT05/C01/T1_SR/LT05_034033_20000913')\n",
        "\n",
        "# Select Red and NIR bands, scale them, and sample 500 points.\n",
        "sampFC = img.select(['B3','B4']).divide(10000).sample(scale=30, numPixels=500)\n",
        "\n",
        "# Arrange the sample as a list of lists.\n",
        "sampDict = sampFC.reduceColumns(ee.Reducer.toList().repeat(2), ['B3', 'B4'])\n",
        "sampList = ee.List(sampDict.get('list'))\n",
        "\n",
        "# Save server-side ee.List as a client-side Python list.\n",
        "sampData = sampList.getInfo()\n",
        "\n",
        "# Display a scatter plot of Red-NIR sample pairs using matplotlib.\n",
        "plt.scatter(sampData[0], sampData[1], alpha=0.2)\n",
        "plt.xlabel('Red', fontsize=12)\n",
        "plt.ylabel('NIR', fontsize=12)\n",
        "plt.show()"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}